package com.sanbi.shield.server.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sanbi.common.util.jwt.JwtTokenUtil;
import com.sanbi.shield.server.biz.param.LoginParam;
import com.sanbi.shield.server.biz.service.AdminService;
import com.sanbi.shield.server.common.exceptions.BizException;
import com.sanbi.shield.server.common.utils.bcrypt.BCryptPasswordEncoder;
import com.sanbi.shield.server.facade.enums.ShieldExceptionMsgEnum;
import com.sanbi.shield.server.jdbc.domain.Admin;
import com.sanbi.shield.server.repository.dao.AdminDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @desc admin Service实现
 * @author wanggang
 * @time 2024/9/14 14:11
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminDao adminDao;

    @Override
    public Admin login(LoginParam loginParam) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<Admin>().eq("username", loginParam.getUsername()).eq("deleted", false);
        Admin admin = adminDao.getOne(wrapper);
        if(null == admin){
            throw new BizException(ShieldExceptionMsgEnum.LOGIN_FAILURE_EXCEPTION);
        }

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(loginParam.getPassword(), admin.getPassword())) {
            throw new BizException(ShieldExceptionMsgEnum.LOGIN_FAILURE_EXCEPTION);
        }

        String token=JwtTokenUtil.generateToken(admin.getId());
        admin.setToken(token);

        return admin;
    }

}
